package com.itheima.mm.task;

import com.itheima.Result;
import com.itheima.common.contants.RabbitMQConstants;
import com.itheima.common.contants.RedisKeyConstants;
import com.itheima.common.safe.AliyunSafeTemplate;
import com.itheima.mm.feign.QuestionFeignApi;
import com.itheima.question.pojo.Question;
import com.itheima.question.pojo.QuestionItem;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Component
@Slf4j
public class AuditTask {

    @Autowired
     private QuestionFeignApi questionFeignApi;

//    @Autowired
//    private RestTemplate restTemplate;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private AliyunSafeTemplate aliyunSafeTemplate;


    //@Scheduled(cron = "* * * * * ?")
    @XxlJob("AutoAudit")
    public void auditQuestion(){
        //1、查询redis中集合的内容,获取待审核的问题id
        Set<String> questionIds = redisTemplate.opsForSet().members(RedisKeyConstants.AUDIT_QUESTION);
        log.info("start question audit, questionIds is : "+questionIds);
        if(questionIds!=null && questionIds.size()>0){
            //2、遍历集合获取到每一个问题的id，根据问题id，
            for (String questionId : questionIds) {
                audit(questionId);
            }
        }
    }

    @Autowired
    private RabbitTemplate rabbitTemplate;

    private void  audit(String questionId){
        // 1、查询 对如下字段内容【st_question表的字段subject + st_question_item的content 】进行文本安全审核
        StringBuilder content = new StringBuilder();//存储文本内容
        List<String> urlList = new ArrayList<>();//存储图片列表
        // 发送http请求：  get请求
        Question question = questionFeignApi.queryById(questionId);
        if(question == null){
            return;
        }
        content.append(question.getSubject());
        if(question.getPicture() != null && question.getPicture().length()>0){
            urlList.add(question.getPicture());
        }

        // 发送http请求：  get请求  http://localhost:9001/question/item/100
        List<QuestionItem> questionItems = questionFeignApi.queryItemById(questionId);


        if(questionItems!=null && questionItems.size() >0 ){
            for (QuestionItem questionItem : questionItems) {
                content.append(questionItem.getContent());
                String picture = questionItem.getPicture();
                if(picture!=null && picture.length()>0){
                    urlList.add(picture);
                }
            }
        }

        try {
            //1、题目的内容审核
            //TextSafeUtil.textSafe(content.toString());
            log.info("question content is "+content.toString());
            Map<String, String> contextResult = aliyunSafeTemplate.greenTextScan(content.toString());
            if(!"pass".equals(contextResult.get("suggestion"))){
                return;
            }
            // 2、图片内容
            log.info("url list is "+urlList);
            if(urlList.size()>0){
                Map<String, String> urlResult = aliyunSafeTemplate.imageScan(urlList);
                if(!"pass".equals(urlResult.get("suggestion"))){
                    return;
                }
            }
            //审核通过，操作： review_status修改这个字段
            question.setReviewStatus("1");
            // put  localhost:9001/question/edit   请求体参数
//            restTemplate.put("http://localhost:9001/question/edit",question);
            Result result = questionFeignApi.editQuestion(question);

            //TODO 审核通过之后，需要将该问题，【使用MQ做异步解耦合】导入到es索引库，后面前端题目的搜索页面就可以搜索到！！
            //方案一： 直接连接es索引库，通过es的api操作es索引库，实现数据的导入。【强耦合】
            //方案二： 题目的id作为一个消息，发送MQ中【结束】
            // 思考： 技术选项：RabbitMQ
            // 哪种交换机：
            // 1、使用默认交换机， 指定队列【方便】  2、fanout【淘汰】  3、direct【】
            // 【后续编写：会有一个程序，单独运行，连接MQ，获取题目的id，完成导入索引库的操作】  【解耦合】
            rabbitTemplate.convertAndSend(
                    RabbitMQConstants.EXCHANGE_QUESTION,
                    RabbitMQConstants.ROUTING_KEY_ES,
                    question.getId());

        } catch (Exception e) {
            e.printStackTrace();
            log.error("audit error!!");
        }finally {
            // redisTemplate.delete(RedisKeyConstants.AUDIT_QUESTION);
        }

    }
}
